import 'package:flutter/material.dart';
import 'dart:io';
import '../models/media_attachment.dart';
import '../constants/app_theme.dart';
import '../constants/app_constants.dart';

/// 媒体预览组件
/// 用于显示和管理媒体附件
class MediaPreview extends StatelessWidget {
  /// 媒体附件列表
  final List<MediaAttachment> attachments;
  
  /// 删除回调
  final Function(MediaAttachment) onRemove;
  
  /// 是否只读模式
  final bool readOnly;
  
  /// 最大显示数量
  final int? maxCount;

  const MediaPreview({
    super.key,
    required this.attachments,
    required this.onRemove,
    this.readOnly = false,
    this.maxCount,
  });

  @override
  Widget build(BuildContext context) {
    final displayAttachments = maxCount != null
        ? attachments.take(maxCount!).toList()
        : attachments;
    
    if (displayAttachments.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 图片网格
        if (displayAttachments.any((a) => a.type == MediaType.image))
          _buildImageGrid(context, displayAttachments),
        
        // 音频列表
        if (displayAttachments.any((a) => a.type == MediaType.audio)) ...[
          if (displayAttachments.any((a) => a.type == MediaType.image))
            const SizedBox(height: 12),
          _buildAudioList(context, displayAttachments),
        ],
        
        // 显示更多提示
        if (maxCount != null && attachments.length > maxCount!) ...[
          const SizedBox(height: 8),
          Text(
            '还有 ${attachments.length - maxCount!} 个附件',
            style: TextStyle(
              color: AppTheme.textSecondaryColor,
              fontSize: 12,
            ),
          ),
        ],
      ],
    );
  }

  /// 构建图片网格
  Widget _buildImageGrid(BuildContext context, List<MediaAttachment> attachments) {
    final images = attachments.where((a) => a.type == MediaType.image).toList();
    
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 8,
        mainAxisSpacing: 8,
        childAspectRatio: 1,
      ),
      itemCount: images.length,
      itemBuilder: (context, index) {
        return _buildImageItem(context, images[index]);
      },
    );
  }

  /// 构建图片项
  Widget _buildImageItem(BuildContext context, MediaAttachment attachment) {
    return GestureDetector(
      onTap: () => _showImageViewer(context, attachment),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: AppTheme.dividerColor,
            width: 1,
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(7),
          child: Stack(
            fit: StackFit.expand,
            children: [
              // 图片
              Image.file(
                File(attachment.filePath),
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: AppTheme.surfaceColor,
                    child: Icon(
                      Icons.broken_image,
                      color: AppTheme.textSecondaryColor,
                    ),
                  );
                },
              ),
              
              // 删除按钮
              if (!readOnly)
                Positioned(
                  top: 4,
                  right: 4,
                  child: GestureDetector(
                    onTap: () => onRemove(attachment),
                    child: Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: Colors.black54,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Icon(
                        Icons.close,
                        color: Colors.white,
                        size: 16,
                      ),
                    ),
                  ),
                ),
              
              // 文件大小
              Positioned(
                bottom: 4,
                left: 4,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 2,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    AppConstants.formatFileSize(attachment.fileSize),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建音频列表
  Widget _buildAudioList(BuildContext context, List<MediaAttachment> attachments) {
    final audios = attachments.where((a) => a.type == MediaType.audio).toList();
    
    return Column(
      children: audios.map((audio) => _buildAudioItem(context, audio)).toList(),
    );
  }

  /// 构建音频项
  Widget _buildAudioItem(BuildContext context, MediaAttachment attachment) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: Row(
        children: [
          // 音频图标
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppTheme.primaryColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Icon(
              Icons.audiotrack,
              color: AppTheme.primaryColor,
              size: 20,
            ),
          ),
          
          const SizedBox(width: 12),
          
          // 音频信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  attachment.fileName,
                  style: TextStyle(
                    color: AppTheme.textPrimaryColor,
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Row(
                  children: [
                    Text(
                      AppConstants.formatFileSize(attachment.fileSize),
                      style: TextStyle(
                        color: AppTheme.textSecondaryColor,
                        fontSize: 12,
                      ),
                    ),
                    if (attachment.duration != null) ...[
                      Text(
                        ' • ',
                        style: TextStyle(
                          color: AppTheme.textSecondaryColor,
                          fontSize: 12,
                        ),
                      ),
                      Text(
                        AppConstants.formatDuration(attachment.duration!),
                        style: TextStyle(
                          color: AppTheme.textSecondaryColor,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ],
                ),
              ],
            ),
          ),
          
          // 播放按钮
          IconButton(
            onPressed: () => _playAudio(context, attachment),
            icon: Icon(
              Icons.play_arrow,
              color: AppTheme.primaryColor,
            ),
          ),
          
          // 删除按钮
          if (!readOnly)
            IconButton(
              onPressed: () => onRemove(attachment),
              icon: Icon(
                Icons.delete_outline,
                color: AppTheme.errorColor,
              ),
            ),
        ],
      ),
    );
  }

  /// 显示图片查看器
  void _showImageViewer(BuildContext context, MediaAttachment attachment) {
    showDialog(
      context: context,
      barrierColor: Colors.black87,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          insetPadding: EdgeInsets.zero,
          child: Stack(
            children: [
              // 图片
              Center(
                child: InteractiveViewer(
                  child: Image.file(
                    File(attachment.filePath),
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        width: 200,
                        height: 200,
                        color: AppTheme.surfaceColor,
                        child: Icon(
                          Icons.broken_image,
                          color: AppTheme.textSecondaryColor,
                          size: 48,
                        ),
                      );
                    },
                  ),
                ),
              ),
              
              // 关闭按钮
              Positioned(
                top: MediaQuery.of(context).padding.top + 16,
                right: 16,
                child: GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              
              // 图片信息
              Positioned(
                bottom: MediaQuery.of(context).padding.bottom + 16,
                left: 16,
                right: 16,
                child: Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        attachment.fileName,
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '大小：${AppConstants.formatFileSize(attachment.fileSize)}',
                        style: const TextStyle(
                          color: Colors.white70,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 播放音频
  void _playAudio(BuildContext context, MediaAttachment attachment) {
    // TODO: 实现音频播放功能
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('播放音频：${attachment.fileName}'),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }
}

/// 紧凑媒体预览组件
/// 用于在列表中显示媒体附件的简化版本
class CompactMediaPreview extends StatelessWidget {
  /// 媒体附件列表
  final List<MediaAttachment> attachments;
  
  /// 最大显示数量
  final int maxCount;
  
  /// 图标大小
  final double iconSize;

  const CompactMediaPreview({
    super.key,
    required this.attachments,
    this.maxCount = 3,
    this.iconSize = 16,
  });

  @override
  Widget build(BuildContext context) {
    if (attachments.isEmpty) {
      return const SizedBox.shrink();
    }

    final displayAttachments = attachments.take(maxCount).toList();
    final hasMore = attachments.length > maxCount;

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        ...displayAttachments.map((attachment) {
          return Padding(
            padding: const EdgeInsets.only(right: 4),
            child: Icon(
              attachment.type == MediaType.image
                  ? Icons.image
                  : Icons.audiotrack,
              size: iconSize,
              color: AppTheme.textSecondaryColor,
            ),
          );
        }),
        
        if (hasMore)
          Text(
            '+${attachments.length - maxCount}',
            style: TextStyle(
              color: AppTheme.textSecondaryColor,
              fontSize: iconSize * 0.75,
            ),
          ),
      ],
    );
  }
}

/// 媒体指示器组件
/// 用于显示媒体附件的数量和类型
class MediaIndicator extends StatelessWidget {
  /// 媒体附件列表
  final List<MediaAttachment> attachments;
  
  /// 图标大小
  final double size;
  
  /// 颜色
  final Color? color;

  const MediaIndicator({
    super.key,
    required this.attachments,
    this.size = 16,
    this.color,
  });

  @override
  Widget build(BuildContext context) {
    if (attachments.isEmpty) {
      return const SizedBox.shrink();
    }

    final imageCount = attachments.where((a) => a.type == MediaType.image).length;
    final audioCount = attachments.where((a) => a.type == MediaType.audio).length;
    final iconColor = color ?? AppTheme.textSecondaryColor;

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (imageCount > 0) ...[
          Icon(
            Icons.image,
            size: size,
            color: iconColor,
          ),
          if (imageCount > 1)
            Text(
              imageCount.toString(),
              style: TextStyle(
                color: iconColor,
                fontSize: size * 0.75,
              ),
            ),
        ],
        
        if (imageCount > 0 && audioCount > 0)
          SizedBox(width: size * 0.5),
        
        if (audioCount > 0) ...[
          Icon(
            Icons.audiotrack,
            size: size,
            color: iconColor,
          ),
          if (audioCount > 1)
            Text(
              audioCount.toString(),
              style: TextStyle(
                color: iconColor,
                fontSize: size * 0.75,
              ),
            ),
        ],
      ],
    );
  }
}